<?php
class Post extends CI_Controller{
	public function index(){
		
		$this->form_validation->set_rules('tieude', 'Tiêu đề', 'required|');
		$this->form_validation->set_rules('parentCat', 'Chuyên mục', 'required');
		$this->form_validation->set_rules('childCat', 'Mục con', 'required');
		$this->form_validation->set_rules('editor', 'Nội dung', 'required');
		if($_SERVER['REQUEST_METHOD'] == 'POST'){
			if($this->form_validation->run() != FALSE){
				
				$result = $this->Post_model->insert(
							$this->input->post('tieude'),
							$this->input->post('editor'),
							$this->input->post('childCat')
							);
				if($result){
					redirect('');
					exit;
				}else{
					$this->load->view('post/index');
				}
			}else{
				$this->load->view('post/index');
			}
			
			
		}else{
			$this->load->view('post/index');	
		}
	}
	
	public function detail($postid){
		$prevUrl = base_url("index.php/post/detail/$postid");
		$this->session->set_userdata('prevURL',$prevUrl);
		
		$data = array();
		
		$post = $this->Post_model->getPostById($postid);
	
		$data['user'] = $this->User_model->getUserById($post->post_author);
		$data['post'] = $post;
		
		$data['answers'] = $this->Post_model->getAnswersByPostId($post->ID);
		
		$data['sameposts'] = $this->Post_model->getPostWithSameCategory($post->post_category);
		
		
		$this->template->write_view('content','post/detail',$data,TRUE);
		$this->template->load();
	}
	
	public function answer(){
		$id = $this->input->post('id');
		$title = $this->input->post('title');
		$text = $this->input->post('text');
		$category = $this->input->post('category');
		$parent_id = $id;
		
		$result = $this->Post_model->insert($title,$text,$category,$parent_id);
		if($result){
			redirect("post/detail/$id");
			exit();
		}
	}
}